/**
 * 项目名称：MSH
 * 包名称：com.mt.common.sys.dao
 * 文件名称：RoleDaoImpl.java
 */
package com.mt.system.daoImpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


import org.springframework.stereotype.Repository;

import com.mt.system.dao.RoleDao;
import com.mt.system.domain.Role;
import com.mt.system.domain.User;


/**
 * 类名称：RoleDaoImpl <br>
 * 类描述： <br>
 * 创建人： 马腾 <br>
 * 创建时间：Oct 18, 2012 12:55:33 PM <br>
 */
@Repository
public class RoleDaoImpl implements RoleDao {
	
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public Role addRole(Role role) {
		entityManager.persist(role);
		return role;
	}

	@Override
	public void updateRole(Role role) {
		entityManager.merge(role);
	}

	@Override
	public void deleteRole(Role role) {
		entityManager.remove(role);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Role> getAllRoles() {
		String eql = "FROM Role role where role.name != 'admin'";
		Query query = entityManager.createQuery(eql);
		return query.getResultList();
	}

	@Override
	public List<Role> getRolesByUser(User user) {
		String eql = "select role from User user join user.roles role where user = :user";
		Query query = entityManager.createQuery(eql);
		query.setParameter("user", user);
		return query.getResultList();
	}

	@Override
	public Role getRoleByName(String name) {
		String eql = "from Role role " +
					 "where role.name = :name";
		Query query = entityManager.createQuery(eql);
		query.setParameter("name", name);
		try {
			return (Role) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public boolean isBindUser(Role role) {
		String eql = "select count(u.id) from User u " +
					 "left join u.roles role " +
					 "where role = :role";
		Query query = entityManager.createQuery(eql);
		query.setParameter("role", role);
		int count = ((Long) query.getSingleResult()).intValue();
		return count > 0;
	}
}
